'use client';

import { useRef, useEffect, useState } from 'react';
import styled from 'styled-components';
import * as Cesium from 'cesium';
import { Viewer, Entity } from 'resium';
import { Cartesian3, Color, Cartographic, Math as CesiumMath } from 'cesium';
import BeidouGridLayer from './BeidouGridLayer';
import RealtimeDroneLayer from './RealtimeDroneLayer';

const MapContainer = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
  
  .cesium-viewer {
    width: 100%;
    height: 100%;
  }
  
  .cesium-viewer-bottom {
    display: none;
  }

  .cesium-widget-credits {
    display: none !important;
  }
  
  .cesium-widget,
  .cesium-widget canvas {
    width: 100% !important;
    height: 100% !important;
    position: absolute;
    top: 0;
    left: 0;
  }
`;

const MapLoadingOverlay = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 21, 41, 0.7);
  color: white;
  font-size: 18px;
  z-index: 100;
`;

// 用于叠加在地图上的信息面板容器
const OverlayContainer = styled.div`
  position: absolute;
  bottom: 20px; /* 调整为贴近底部 */
  left: calc(22% + 20px); /* 精确定位到左侧面板右侧 */
  background-color: rgba(0, 21, 41, 0.6);
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 5px;
  padding: 8px;
  z-index: 15; /* 高于UI层 */
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: white;
  max-width: 180px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  
  @media (max-height: 768px) {
    bottom: 15px; /* 在小屏幕上调整位置 */
    max-width: 160px;
    font-size: 11px;
  }
`;

// 地图工具栏
const MapToolbar = styled.div`
  position: absolute;
  top: 90px; /* 避开顶部导航栏 */
  left: calc(22% + 20px); /* 精确定位到左侧面板右侧 */
  background-color: rgba(0, 21, 41, 0.6);
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中所有子元素 */
  padding: 8px;
  gap: 8px;
  z-index: 15; /* 高于UI层 */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  
  @media (max-height: 768px) {
    top: 85px; /* 在小屏幕上调整位置 */
  }
`;

// 地图工具按钮
const ToolButton = styled.button`
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center; /* 垂直居中内容 */
  justify-content: center; /* 水平居中内容 */
  background-color: rgba(24, 144, 255, 0.3);
  color: white;
  border: 1px solid rgba(24, 144, 255, 0.7);
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.2s ease;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  margin: 0 auto; /* 确保按钮水平居中 */
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.5);
    transform: translateY(-2px);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.4);
  }
  
  &:active {
    transform: translateY(0);
    background-color: rgba(24, 144, 255, 0.7);
  }
  
  @media (max-height: 768px) {
    width: 30px;
    height: 30px;
    font-size: 14px;
  }
`;

// 坐标信息样式
const CoordinateInfo = styled.div`
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  white-space: nowrap;
`;

// 标签样式
const Label = styled.span`
  color: #a0cfff;
  margin-right: 5px;
`;

// 值样式
const Value = styled.span`
  color: white;
  font-weight: 500;
`;

// 添加组件标题样式
const ComponentTitle = styled.div`
  font-size: 12px;
  color: #a0cfff;
  margin-bottom: 5px;
  text-align: center; /* 确保文本居中 */
  font-weight: 500;
  letter-spacing: 1px;
  border-bottom: 1px solid rgba(24, 144, 255, 0.3);
  padding-bottom: 3px;
  width: 100%; /* 确保标题占满宽度 */
`;

// 添加固定位置的无人机信息气泡样式
const DroneInfoBubble = styled.div`
  position: absolute;
  right: 480px; /* 修改位置，贴近飞行计划面板左侧，保留20px间隙 */
  bottom: 20px;
  width: 270px;
  background: rgba(38, 38, 38, 0.95);
  color: white;
  padding: 10px;
  border-radius: 5px;
  font-family: Arial;
  box-shadow: 0 0 10px rgba(0,0,0,0.5);
  border: 1px solid #00b7ff;
  z-index: 20;
  display: none; /* 默认不显示 */
  
  .bubble-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    font-size: 13px;
    color: #00b7ff;
    margin-bottom: 6px;
    border-bottom: 1px solid #444;
    padding-bottom: 4px;
  }
  
  .close-btn {
    cursor: pointer;
    font-size: 16px;
    color: #aaa;
    transition: color 0.2s;
    
    &:hover {
      color: white;
    }
  }
  
  table {
    width: 100%;
    font-size: 11px;
    border-spacing: 0 4px;
  }
  
  td:first-child {
    color: #aaa;
    width: 80px;
  }
`;

// 地图位置类型定义
interface MapPosition {
  longitude: number;
  latitude: number;
  height: number;
  heading: number;
  pitch: number;
  roll: number;
}

// 初始位置 - 江门市中心
const initialPosition = {
  longitude: 113.061859,
  latitude: 22.565006,
  height: 5000,
  heading: 0,
  pitch: -45,
  roll: 0
};

// 添加天地图密钥和常量
// 中科星图作为备选
// const SMAP_URL = 'https://webst{s}.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}';
// const SMAP_ANNO_URL = 'https://webst{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}';

// const SMAP_URL = 'https://tiles2.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=a979b0c052771f21ecb55a4307fce0f6d50176ce448ea02c9bff585898473ac3';
const SMAP_URL = 'https://www.supermapol.com/proxy/y8f150ad/iserver/services/map-geovis-img/rest/maps/GEOVIS_Img/zxyTileImage.png?x={x}&y={y}&z={z}';

// const SMAP_ANNO_URL = 'https://tiles1.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=png&tmsIds=w&token=a979b0c052771f21ecb55a4307fce0f6d50176ce448ea02c9bff585898473ac3';
const SMAP_ANNO_URL = 'https://www.supermapol.com/proxy/g2yw6g0o/iserver/services/map-geovis-cia/rest/maps/GEOVIS_Cia/zxyTileImage.png?x={x}&y={y}&z={z}'
// 添加Cesium全局变量的类型声明
declare global {
  interface Window {
    Cesium: typeof Cesium;
    CESIUM_BASE_URL: string;
  }
}

// 添加一个脚本加载工具函数
const loadScript = (src: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (document.querySelector(`script[src="${src}"]`)) {
      resolve(); // 脚本已存在
      return;
    }

    const script = document.createElement('script');
    script.src = src;
    script.onload = () => resolve();
    script.onerror = () => reject(new Error(`加载脚本失败: ${src}`));
    document.head.appendChild(script);
  });
};

export default function CesiumMap() {
  // console.log('CesiumMap组件渲染');
  const viewerRef = useRef<Cesium.Viewer | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [position, setPosition] = useState<MapPosition>(initialPosition);
  const [mousePosition, setMousePosition] = useState<{longitude: number; latitude: number; height: number} | null>(null);
  const [terrainEnabled, setTerrainEnabled] = useState<boolean>(false);
  const [terrainLoading, setTerrainLoading] = useState<boolean>(false);
  const [isSatelliteMap, setIsSatelliteMap] = useState<boolean>(true);
  const [isAnnotationVisible, setIsAnnotationVisible] = useState<boolean>(false);
  const [isGridVisible, setIsGridVisible] = useState<boolean>(false);
  const [gridLevel, setGridLevel] = useState<number>(2); // 默认二级网格
  const annotationLayerRef = useRef<Cesium.ImageryLayer | null>(null);
  
  // 添加一个状态来跟踪Cesium是否已经初始化
  const [cesiumLoaded, setCesiumLoaded] = useState(false);
  
  const [showDroneInfo, setShowDroneInfo] = useState<boolean>(false);
  const [droneInfoData, setDroneInfoData] = useState<{
    longitude: number;
    latitude: number;
    height: number;
    sn: string;
    regCode: string;
    owner: string;
    organization: string;
    model: string;
    purpose: string;
  } | null>(null);
  
  // 初始化Cesium配置
  useEffect(() => {
    // 确保我们在客户端环境
    if (typeof window === 'undefined') return;
    
    const initCesium = async () => {
      try {
        // 检查全局Cesium对象是否已定义
        if (!window.Cesium) {
          console.log('Cesium不存在，尝试加载脚本...');
          
          // 确保CESIUM_BASE_URL已设置
          if (!window.CESIUM_BASE_URL) {
            window.CESIUM_BASE_URL = '/cesium/';
            console.log('已设置CESIUM_BASE_URL:', window.CESIUM_BASE_URL);
          }
          
          // 如果Cesium不存在，尝试动态加载脚本
          try {
            await loadScript('/cesium/Cesium.js');
            console.log('动态加载Cesium脚本成功');
          } catch (err) {
            console.error('动态加载Cesium脚本失败:', err);
            setError('加载地图资源失败，请刷新页面重试');
            setIsLoading(false);
            return;
          }
        }
        
        // 再次检查Cesium是否已加载
        if (!window.Cesium) {
          console.error('Cesium脚本已加载但window.Cesium未定义');
          setError('初始化地图资源失败，请刷新页面重试');
          setIsLoading(false);
          return;
        }
        
        // 设置访问令牌 - 建议移动到环境变量中
        window.Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmZkZWNlZC0zMGFlLTRkNjEtODczNS0wM2UwNzIzZTgzOWQiLCJpZCI6Mjg5NDY0LCJpYXQiOjE3NDY1NzQ0MjJ9.AqUCB4gsgFQcN4lW-vmsosO3wcGLSTTiHNLGq4GRrQg';
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmZkZWNlZC0zMGFlLTRkNjEtODczNS0wM2UwNzIzZTgzOWQiLCJpZCI6Mjg5NDY0LCJpYXQiOjE3NDY1NzQ0MjJ9.AqUCB4gsgFQcN4lW-vmsosO3wcGLSTTiHNLGq4GRrQg';
        window.CESIUM_BASE_URL = '/cesium/';

        // 标记Cesium已加载完成
        setCesiumLoaded(true);
        console.log('Cesium初始化成功');
        
        // 短延迟后隐藏加载界面
        setTimeout(() => {
          setIsLoading(false);
        }, 1500);
      } catch (err) {
        console.error('初始化Cesium时发生错误:', err);
        setError('初始化地图时发生错误，请刷新页面重试');
        setIsLoading(false);
      }
    };
    
    initCesium();
    
    // 清理函数
    return () => {
      // 如果有清理工作需要执行，可以在这里添加
    };
  }, []);
  
  // 仅在Cesium加载完成后渲染地图
  if (isLoading || !cesiumLoaded) {
    return (
      <MapContainer>
        <MapLoadingOverlay>
          {error ? error : '正在加载地图资源，请稍候...'}
        </MapLoadingOverlay>
      </MapContainer>
    );
  }
  
  // 如果有错误但加载已完成
  if (error && !isLoading) {
    return (
      <MapContainer>
        <MapLoadingOverlay>
          {error}
          <button 
            onClick={() => window.location.reload()} 
            style={{ 
              marginTop: '20px', 
              padding: '8px 16px', 
              background: 'rgba(24, 144, 255, 0.7)',
              border: 'none',
              borderRadius: '4px',
              color: 'white',
              cursor: 'pointer'
            }}
          >
            刷新页面
          </button>
        </MapLoadingOverlay>
      </MapContainer>
    );
  }
  
  // 处理Cesium Viewer的引用
  const handleViewerReady = (viewer: Cesium.Viewer) => {
    viewerRef.current = viewer;
    
    if (viewer) {
      // 移除默认的工具栏和信息面板
      if (viewer.cesiumWidget.creditContainer) {
        const creditContainer = viewer.cesiumWidget.creditContainer as HTMLElement;
        creditContainer.style.display = 'none';
      }
      
      // 添加默认卫星底图
      try {
        // 由于是异步函数，需要使用Promise
        addSatelliteMap().catch(e => {
          console.error('初始化添加卫星地图失败:', e);
        });
      } catch (e) {
        console.error('添加影像图层失败:', e);
      }
      
      // 当相机变化时更新位置信息
      viewer.camera.changed.addEventListener(() => {
        updatePositionFromCamera(viewer.camera);
      });
      
      // 监听鼠标移动事件，更新鼠标位置信息
      viewer.screenSpaceEventHandler.setInputAction((movement: Cesium.ScreenSpaceEventHandler.MotionEvent) => {
        const cartesian = viewer.scene.pickPosition(movement.endPosition);
        if (cartesian) {
          const cartographic = Cartographic.fromCartesian(cartesian);
          const longitude = CesiumMath.toDegrees(cartographic.longitude);
          const latitude = CesiumMath.toDegrees(cartographic.latitude);
          const height = cartographic.height;
          
          // 设置鼠标位置
          setMousePosition({
            longitude,
            latitude,
            height: height > 0 ? height : 0 // 确保高度不为负
          });
        } else {
          // 如果未找到位置，使用射线拾取
          const ray = viewer.camera.getPickRay(movement.endPosition);
          if (ray) {
            const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            if (cartesian) {
              const cartographic = Cartographic.fromCartesian(cartesian);
              const longitude = CesiumMath.toDegrees(cartographic.longitude);
              const latitude = CesiumMath.toDegrees(cartographic.latitude);
              const height = cartographic.height;
              
              setMousePosition({
                longitude,
                latitude,
                height: height > 0 ? height : 0
              });
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      
      // 仅在初始化时设置一次视角
      viewer.camera.setView({
        destination: Cartesian3.fromDegrees(
          initialPosition.longitude, 
          initialPosition.latitude, 
          initialPosition.height
        ),
        orientation: {
          heading: CesiumMath.toRadians(initialPosition.heading),
          pitch: CesiumMath.toRadians(initialPosition.pitch),
          roll: CesiumMath.toRadians(initialPosition.roll)
        }
      });
      
      // 禁用自动重置视图
      viewer.scene.screenSpaceCameraController.enableInputs = true;
      viewer.scene.screenSpaceCameraController.enableRotate = true;
      viewer.scene.screenSpaceCameraController.enableTranslate = true;
      viewer.scene.screenSpaceCameraController.enableZoom = true;
      viewer.scene.screenSpaceCameraController.enableTilt = true;
      viewer.scene.screenSpaceCameraController.enableLook = true;
      
      // 默认不启用3D地形
      // 如果需要开启地形，可以调用enableTerrain()
      
      // 创建城市低空巡检飞行航线
      // createDronePatrolRoute(viewer);
      
      // 创建禁飞区电子围栏
      // createNoFlyZoneFence(viewer);
      
      // 添加雷达监控站
      createRadarStation(viewer);
      
      // 加载禁飞区数据并创建多边形
      createFlyZonesFromJSON(viewer);
    }
  };
  
  // 更新相机位置信息
  const updatePositionFromCamera = (camera: Cesium.Camera) => {
    const position = camera.position;
    const cartographic = Cartographic.fromCartesian(position);
    
    const longitude = CesiumMath.toDegrees(cartographic.longitude);
    const latitude = CesiumMath.toDegrees(cartographic.latitude);
    const height = cartographic.height;
    
    // 获取相机方向
    const heading = CesiumMath.toDegrees(camera.heading);
    const pitch = CesiumMath.toDegrees(camera.pitch);
    const roll = CesiumMath.toDegrees(camera.roll);
    
    setPosition({
      longitude,
      latitude,
      height,
      heading,
      pitch,
      roll
    });
  };
  
  // 地图控制方法
  const handleZoomIn = () => {
    if (viewerRef.current) {
      const cameraPosition = viewerRef.current.camera.position;
      const cameraDirection = viewerRef.current.camera.direction;
      
      // 计算新位置 - 沿视线方向前进
      const moveDistance = position.height * 0.2; // 根据高度移动一个比例
      const scaledDirection = Cartesian3.multiplyByScalar(
        cameraDirection, 
        moveDistance, 
        new Cartesian3()
      );
      
      const newPosition = Cartesian3.add(
        cameraPosition, 
        scaledDirection, 
        new Cartesian3()
      );
      
      // 飞向新位置
      viewerRef.current.camera.flyTo({
        destination: newPosition,
        duration: 0.5
      });
    }
  };

  const handleZoomOut = () => {
    if (viewerRef.current) {
      const cameraPosition = viewerRef.current.camera.position;
      const cameraDirection = viewerRef.current.camera.direction;
      
      // 计算新位置 - 沿视线反方向后退
      const moveDistance = position.height * 0.2; // 根据高度移动一个比例
      const reverseDirection = Cartesian3.negate(
        cameraDirection, 
        new Cartesian3()
      );
      const scaledDirection = Cartesian3.multiplyByScalar(
        reverseDirection, 
        moveDistance, 
        new Cartesian3()
      );
      
      const newPosition = Cartesian3.add(
        cameraPosition, 
        scaledDirection, 
        new Cartesian3()
      );
      
      // 飞向新位置
      viewerRef.current.camera.flyTo({
        destination: newPosition,
        duration: 0.5
      });
    }
  };

  const handleResetView = () => {
    if (viewerRef.current) {
      viewerRef.current.camera.flyTo({
        destination: Cartesian3.fromDegrees(
          initialPosition.longitude, 
          initialPosition.latitude, 
          initialPosition.height
        ),
        orientation: {
          heading: CesiumMath.toRadians(initialPosition.heading),
          pitch: CesiumMath.toRadians(initialPosition.pitch),
          roll: CesiumMath.toRadians(initialPosition.roll)
        },
        duration: 2.0
      });
    }
  };
  
  // 启用地形
  const enableTerrain = async () => {
    try {
      if (viewerRef.current) {
        // 设置地形加载中状态
        setTerrainLoading(true);
        
        // 记录当前相机位置
        const currentPosition = viewerRef.current.camera.position;
        const currentCartographic = Cartographic.fromCartesian(currentPosition);
        const currentLongitude = CesiumMath.toDegrees(currentCartographic.longitude);
        const currentLatitude = CesiumMath.toDegrees(currentCartographic.latitude);
        const currentHeight = currentCartographic.height;
        
        // 尝试使用Cesium世界地形
        const terrainProvider = await Cesium.createWorldTerrainAsync({
          requestWaterMask: true,
          requestVertexNormals: true
        });

        // 设置地形提供者
        viewerRef.current.terrainProvider = terrainProvider;
        // viewerRef.current.terrainProvider = new Cesium.CesiumTerrainProvider({
        //   url: Cesium.IonResource.fromAssetId(1)
        // });
        setTerrainEnabled(true);
        
        // 等待地形加载完成后调整相机位置
        setTimeout(() => {
          if (viewerRef.current) {
            // 获取相机方向
            const heading = viewerRef.current.camera.heading;
            const pitch = viewerRef.current.camera.pitch;
            const roll = viewerRef.current.camera.roll;
            
            // 确保相机高度在地形之上
            const targetHeight = Math.max(currentHeight, 3000); // 增加高度防止陷入地形
            
            // 飞向适当的视角
            viewerRef.current.camera.flyTo({
              destination: Cartesian3.fromDegrees(
                currentLongitude,
                currentLatitude,
                targetHeight
              ),
              orientation: {
                heading: heading,
                pitch: pitch,
                roll: roll
              },
              duration: 1.0,
              complete: () => {
                // 地形加载完成
                setTerrainLoading(false);
              }
            });
          } else {
            setTerrainLoading(false);
          }
        }, 1000); // 给地形加载一秒的时间
        
        setError(null); // 清除任何已有错误
      }
    } catch (e) {
      console.error("无法加载地形数据:", e);
      // 备用方案：使用椭球体地形
      if (viewerRef.current) {
        viewerRef.current.terrainProvider = new Cesium.EllipsoidTerrainProvider();
        setTerrainEnabled(false);
        setError("地形数据加载失败，已切换到平面地图");
      }
      setTerrainLoading(false);
    }
  };
  
  // 禁用地形
  const disableTerrain = () => {
    if (viewerRef.current) {
      viewerRef.current.terrainProvider = new Cesium.EllipsoidTerrainProvider();
      setTerrainEnabled(false);
      setTerrainLoading(false);
    }
  };
  
  // 地形显示切换
  const toggleTerrain = () => {
    if (viewerRef.current && !terrainLoading) {
      const newTerrainState = !terrainEnabled;
      
      if (newTerrainState) {
        enableTerrain();
      } else {
        disableTerrain();
      }
    }
  };
  
  // 添加矢量地图
  const addVectorMap = async () => {
    if (viewerRef.current) {
      try {
        // 清除所有影像图层
        viewerRef.current.imageryLayers.removeAll();
        
        // 尝试使用中科星图矢量图层
        // 添加中科星图底图
        const vecProvider = new Cesium.UrlTemplateImageryProvider({
          url: SMAP_URL,
          subdomains: ['01', '02', '03', '04'],
          tilingScheme: new Cesium.WebMercatorTilingScheme(),
          maximumLevel: 18
        });
        viewerRef.current.imageryLayers.addImageryProvider(vecProvider);
        
        // 添加中科星图注记，并保留其显示状态
        const cvaProvider = new Cesium.UrlTemplateImageryProvider({
          url: SMAP_ANNO_URL,
          subdomains: ['01', '02', '03', '04'],
          tilingScheme: new Cesium.WebMercatorTilingScheme(),
          maximumLevel: 18
        });
        annotationLayerRef.current = viewerRef.current.imageryLayers.addImageryProvider(cvaProvider);
        
        // 设置注记图层的显示状态
        if (annotationLayerRef.current && !isAnnotationVisible) {
          annotationLayerRef.current.show = false;
        }
        
        setIsSatelliteMap(false);
      } catch (e) {
        console.error('添加矢量图层失败:', e);
        // 错误处理：尝试直接加载默认图层
        try {
          const defaultImagery = await Cesium.createWorldImageryAsync();
          viewerRef.current.imageryLayers.addImageryProvider(defaultImagery);
        } catch (innerError) {
          console.error('添加备用影像失败:', innerError);
        }
      }
    }
  };
  
  // 添加卫星地图
  const addSatelliteMap = async () => {
    if (viewerRef.current) {
      try {
        // 清除所有影像图层
        viewerRef.current.imageryLayers.removeAll();
        
        // 使用高德卫星影像
        // 添加高德卫星影像底图
        const imgProvider = new Cesium.UrlTemplateImageryProvider({
          url: SMAP_URL,
          subdomains: ['01', '02', '03', '04'],
          tilingScheme: new Cesium.WebMercatorTilingScheme(),
          maximumLevel: 18
        });
        viewerRef.current.imageryLayers.addImageryProvider(imgProvider);
        
        // 添加高德影像注记，并保留其显示状态
        const ciaProvider = new Cesium.UrlTemplateImageryProvider({
          url: SMAP_ANNO_URL,
          subdomains: ['01', '02', '03', '04'],
          tilingScheme: new Cesium.WebMercatorTilingScheme(),
          maximumLevel: 18
        });
        annotationLayerRef.current = viewerRef.current.imageryLayers.addImageryProvider(ciaProvider);
        
        // 设置注记图层的显示状态
        if (annotationLayerRef.current && !isAnnotationVisible) {
          annotationLayerRef.current.show = false;
        }
        
        setIsSatelliteMap(true);
      } catch (e) {
        console.error('添加卫星影像图层失败:', e);
        // 失败时回退到矢量地图
        addVectorMap();
      }
    }
  };
  
  // 切换地图类型
  const toggleMapType = () => {
    if (viewerRef.current) {
      if (isSatelliteMap) {
        // 由于是异步函数，需要处理Promise
        addVectorMap().catch(e => {
          console.error('切换矢量地图失败:', e);
        });
      } else {
        // 由于是异步函数，需要使用then来处理
        addSatelliteMap().catch(e => {
          console.error('切换卫星地图失败:', e);
        });
      }
    }
  };
  
  // 切换注记图层显示/隐藏
  const toggleAnnotation = () => {
    if (annotationLayerRef.current) {
      const newVisibility = !isAnnotationVisible;
      annotationLayerRef.current.show = newVisibility;
      setIsAnnotationVisible(newVisibility);
    }
  };
  
  // 切换网格显示
  const toggleGrid = () => {
    setIsGridVisible(!isGridVisible);
  };
  
  // 切换网格级别
  const cycleGridLevel = () => {
    const newLevel = gridLevel >= 5 ? 1 : gridLevel + 1;
    setGridLevel(newLevel);
  };
  
  // 创建随机航点生成城市低空巡检飞行航线
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const createDronePatrolRoute = (viewer: Cesium.Viewer) => {
    // 基于初始位置创建航点
    const basePosition = {
      longitude: initialPosition.longitude,
      latitude: initialPosition.latitude
    };
    
    // 无人机飞行高度 (120米)
    const flightHeight = 120;
    
    // 创建10个航点
    const waypointsCount = 10;
    const waypoints = [];
    
    // 计算一公里在经度和纬度上的近似值（在当前纬度下）
    const oneDegreeLatInMeters = 111000; // 纬度1度约为111km
    const oneDegreeLonInMeters = 111000 * Math.cos(CesiumMath.toRadians(basePosition.latitude)); // 根据纬度调整经度1度的距离
    
    // 计算3公里的经纬度范围
    const kmRange = 1.5; // 半径1.5公里
    const latRange = kmRange * 1000 / oneDegreeLatInMeters;
    const lonRange = kmRange * 1000 / oneDegreeLonInMeters;
    
    // 生成随机航点，形成一个3公里长的闭环路径
    for (let i = 0; i < waypointsCount; i++) {
      // 使用正弦和余弦函数生成一个环形的路径
      const angle = (i / waypointsCount) * Math.PI * 2; // 均匀分布在圆上
      const distance = Math.random() * 0.3 + 0.7; // 0.7-1.0之间的随机值，确保不会太靠近中心
      
      const offsetLon = Math.cos(angle) * lonRange * distance;
      const offsetLat = Math.sin(angle) * latRange * distance;
      
      // 添加随机扰动
      const jitterLon = (Math.random() - 0.5) * lonRange * 0.3;
      const jitterLat = (Math.random() - 0.5) * latRange * 0.3;
      
      waypoints.push({
        longitude: basePosition.longitude + offsetLon + jitterLon,
        latitude: basePosition.latitude + offsetLat + jitterLat,
        height: flightHeight
      });
    }
    
    // 创建航线路径
    const positions = waypoints.map(wp => 
      Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height)
    );
    
    // 将首尾相连形成闭环
    positions.push(positions[0]);
    
    // 添加巡检路径
    viewer.entities.add({
      name: '城市低空巡检航线',
      polyline: {
        positions: positions,
        width: 5,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.2,
          color: Color.CYAN
        }),
        clampToGround: false
      }
    });
    
    // 添加航点标记
    for (let i = 0; i < waypointsCount; i++) {
      const wp = waypoints[i];
      
      viewer.entities.add({
        name: `航点${i+1}`,
        position: Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height),
        point: {
          pixelSize: 10,
          color: Color.WHITE,
          outlineColor: Color.CYAN,
          outlineWidth: 2
        },
        label: {
          text: `WP${i+1}`,
          font: '14px sans-serif',
          fillColor: Color.WHITE,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          outlineColor: Color.BLACK,
          pixelOffset: new Cesium.Cartesian2(0, -20),
          showBackground: true,
          backgroundColor: new Color(0, 0, 0, 0.7),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        }
      });
    }
    
    // 添加无人机模型
    createDroneEntity(viewer, waypoints);
    
    // 添加航线信息面板
    viewer.entities.add({
      name: '航线信息',
      position: Cartesian3.fromDegrees(
        basePosition.longitude,
        basePosition.latitude,
        flightHeight + 50 // 在航线上方50米显示
      ),
      billboard: {
        image: undefined, // 无图像
        show: false
      },
      label: {
        text: '城市低空巡检航线\n长度: 约3公里\n高度: 120米\n航点数: 10',
        font: '16px sans-serif',
        fillColor: Color.WHITE,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth: 2,
        outlineColor: Color.BLACK,
        showBackground: true,
        backgroundColor: new Color(0, 0, 0, 0.7),
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, -20),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
  };

  // 创建无人机实体并让其沿航线飞行
  const createDroneEntity = (viewer: Cesium.Viewer, waypoints: {longitude: number, latitude: number, height: number}[]) => {
    // 创建一个组合的时间序列，用于动画
    const totalSeconds = 120; // 完成整个路径需要的总时间（秒）
    const property = new Cesium.SampledPositionProperty();
    
    const start = Cesium.JulianDate.fromDate(new Date());
    const stop = Cesium.JulianDate.addSeconds(start, totalSeconds, new Cesium.JulianDate());
    
    // 设置查看器时间范围
    viewer.clock.startTime = start.clone();
    viewer.clock.stopTime = stop.clone();
    viewer.clock.currentTime = start.clone();
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; // 循环播放
    viewer.clock.multiplier = 1;
    
    // 构建路径上的样本点
    const positionsCartesian = waypoints.map(wp => 
      Cartesian3.fromDegrees(wp.longitude, wp.latitude, wp.height)
    );
    
    // 将首位重复以形成闭环
    positionsCartesian.push(positionsCartesian[0]);
    
    // 计算每个航段的时间
    const timeStepSize = totalSeconds / positionsCartesian.length;
    
    // 为每个点添加时间样本 - 使用线性插值以确保直线飞行
    for (let i = 0; i < positionsCartesian.length; i++) {
      const time = Cesium.JulianDate.addSeconds(start, i * timeStepSize, new Cesium.JulianDate());
      property.addSample(time, positionsCartesian[i]);
    }
    
    // 设置插值选项，使用线性插值确保直线飞行
    property.setInterpolationOptions({
      interpolationDegree: 1, // 使用线性插值
      interpolationAlgorithm: Cesium.LinearApproximation
    });
    
    // 计算并设置方向（朝向）
    const orientationProperty = new Cesium.VelocityOrientationProperty(property);
    
    // 无人机的静态信息
    const droneInfo = {
      sn: "UAV20240801-001",
      regCode: "CAAC-XC-20240801001", // 民航局实名登记标志
      owner: "张伟明",
      organization: "江门市空管局",
      model: "DJI Mavic 3T",
      purpose: "城市低空巡检"
    };
    
    // 创建无人机实体
    const drone = viewer.entities.add({
      name: '巡检无人机',
      position: property,
      orientation: orientationProperty,
      billboard: {
        image: '', // 无人机图标（SVG格式）
        width: 32,
        height: 32,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        disableDepthTestDistance: 5000.0, // 确保标记始终可见
        scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 15000, 0.7) // 远处缩小
      },
      label: {
        text: droneInfo.sn,
        font: '12px sans-serif',
        fillColor: Color.WHITE,
        outlineColor: Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.TOP,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, -40), // 位于图标上方
        showBackground: true,
        backgroundColor: new Color(0, 0, 0, 0.7),
        backgroundPadding: new Cesium.Cartesian2(7, 5),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      path: {
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          taperPower: 1.0,
          color: Color.YELLOW
        }),
        width: 10,
        leadTime: 0,
        trailTime: 60,
        show: true
      }
    });
    
    // 回调函数更新无人机信息
    const updateDroneInfo = () => {
      if (!drone || !viewer.clock.shouldAnimate) return;
      
      // 获取当前时间点的位置
      const currentPosition = property.getValue(viewer.clock.currentTime, new Cesium.Cartesian3());
      if (!currentPosition) return;
      
      // 转换为经纬度高度
      const cartographic = Cartographic.fromCartesian(currentPosition);
      const longitude = CesiumMath.toDegrees(cartographic.longitude);
      const latitude = CesiumMath.toDegrees(cartographic.latitude);
      const height = cartographic.height;
      
      // 更新信息到状态
      setDroneInfoData({
        longitude,
        latitude,
        height,
        ...droneInfo
      });
    };
    
    // 添加预渲染事件监听器，实时更新无人机信息
    viewer.scene.preRender.addEventListener(updateDroneInfo);
    
    // 启动动画
    viewer.clock.shouldAnimate = true;
    
    // 当点击无人机时，显示信息气泡
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction((click: Cesium.ScreenSpaceEventHandler.PositionedEvent) => {
      const pickedObject = viewer.scene.pick(click.position);
      if (Cesium.defined(pickedObject) && pickedObject.id === drone) {
        // 如果点击的是无人机，则显示信息气泡
        setShowDroneInfo(true);
        
        // 可选：聚焦相机到无人机
        const dronePosition = property.getValue(viewer.clock.currentTime, new Cesium.Cartesian3());
        if (dronePosition) {
          viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromElements(
              dronePosition.x,
              dronePosition.y,
              dronePosition.z + 200 // 比无人机高200米
            ),
            orientation: {
              heading: viewer.camera.heading,
              pitch: Cesium.Math.toRadians(-30), // 俯视角度
              roll: 0
            },
            duration: 1.0
          });
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    // 初始化信息内容
    updateDroneInfo();
    
    // 清理函数，组件卸载时移除事件监听
    const cleanup = () => {
      viewer.scene.preRender.removeEventListener(updateDroneInfo);
      handler.destroy();
    };
    
    // 存储清理函数用于后续清理
    (drone as Cesium.Entity & { _cleanup: () => void })._cleanup = cleanup;
    
    return drone;
  };
  
  // 创建禁飞区电子围栏
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const createNoFlyZoneFence = (viewer: Cesium.Viewer) => {
    // 使用偏移后的位置为中心 - 设置为航线旁边
    const center = {
      longitude: initialPosition.longitude + 0.015, // 向东偏移
      latitude: initialPosition.latitude - 0.01    // 向南偏移
    };
    
    // 计算一公里在经纬度上的近似值（在当前纬度下）
    const oneDegreeLatInMeters = 111000; // 纬度1度约为111km
    const oneDegreeLonInMeters = 111000 * Math.cos(CesiumMath.toRadians(center.latitude)); // 根据纬度调整经度1度的距离
    
    // 计算1公里正方形的经纬度范围
    const sideLength = 500.0; // 1公里
    const latOffset = (sideLength / 2) / oneDegreeLatInMeters; // 半边长的纬度偏移
    const lonOffset = (sideLength / 2) / oneDegreeLonInMeters; // 半边长的经度偏移
    
    // 围栏高度
    const fenceHeight = 120;
    
    // 创建正方形的四个角点坐标（顺时针）
    const corners = [
      { lon: center.longitude - lonOffset, lat: center.latitude - latOffset }, // 左下
      { lon: center.longitude + lonOffset, lat: center.latitude - latOffset }, // 右下
      { lon: center.longitude + lonOffset, lat: center.latitude + latOffset }, // 右上
      { lon: center.longitude - lonOffset, lat: center.latitude + latOffset }  // 左上
    ];
    
    // 为每个墙面添加不同的材质，实现更丰富的视觉效果
    const createWallMaterial = (index: number) => {
      // 使用不同的材质类型为不同的墙面
      switch (index % 4) {
        case 0:
          // 条纹材质，垂直条纹
          return new Cesium.StripeMaterialProperty({
            evenColor: Cesium.Color.RED.withAlpha(0.7),
            oddColor: Cesium.Color.RED.withAlpha(0.3),
            repeat: 10,
            orientation: Cesium.StripeOrientation.VERTICAL
          });
        case 1:
          // 网格材质，红色网格
          return new Cesium.GridMaterialProperty({
            color: Cesium.Color.RED.withAlpha(0.5),
            cellAlpha: 0.2,
            lineCount: new Cesium.Cartesian2(4, 8),
            lineThickness: new Cesium.Cartesian2(2.0, 2.0),
            lineOffset: new Cesium.Cartesian2(0.0, 0.0)
          });
        case 2:
          // 扫描线，水平移动的光线
          return new Cesium.StripeMaterialProperty({
            evenColor: Cesium.Color.RED.withAlpha(0.3),
            oddColor: Cesium.Color.RED.withAlpha(0.8),
            repeat: 1,
            orientation: Cesium.StripeOrientation.HORIZONTAL
          });
        case 3:
          // 条纹材质，斜向条纹
          return new Cesium.StripeMaterialProperty({
            evenColor: Cesium.Color.RED.withAlpha(0.7),
            oddColor: Cesium.Color.RED.withAlpha(0.3),
            repeat: 8,
            orientation: Cesium.StripeOrientation.HORIZONTAL // Cesium只支持HORIZONTAL和VERTICAL两种方向
          });
        default:
          return Cesium.Color.RED.withAlpha(0.6);
      }
    };

    // 创建四条墙面实体（每条墙面从一个角点到另一个角点）
    const walls: Cesium.Entity[] = [];

    for (let i = 0; i < 4; i++) {
      // 获取当前角点和下一个角点
      const cornerA = corners[i];
      const cornerB = corners[(i + 1) % 4];
      
      // 创建墙面坐标数组（只需要两个点，高度由 minimumHeights 和 maximumHeights 控制）
      const wallPositions = [
        Cartesian3.fromDegrees(cornerA.lon, cornerA.lat, 0),
        Cartesian3.fromDegrees(cornerB.lon, cornerB.lat, 0)
      ];
      
      // 创建墙面实体 - 使用更好的光效材质
      const wallEntity = viewer.entities.add({
        name: `禁飞区墙面${i+1}`,
        wall: {
          positions: wallPositions,
          minimumHeights: [0, 0], // 底部高度为0
          maximumHeights: [fenceHeight, fenceHeight], // 顶部高度为120米
          material: createWallMaterial(i), // 使用更高级的材质
          outline: true,
          outlineColor: Cesium.Color.RED.withAlpha(0.8),
          outlineWidth: 2.0
        }
      });
      
      walls.push(wallEntity);
    }
    
    // 为每个角点添加垂直的发光线（边缘线）
    const verticalLines: Cesium.Entity[] = [];
    
    for (let i = 0; i < 4; i++) {
      const corner = corners[i];
      
      // 创建从底部到顶部的垂直线
      const bottomPos = Cartesian3.fromDegrees(corner.lon, corner.lat, 0);
      const topPos = Cartesian3.fromDegrees(corner.lon, corner.lat, fenceHeight);
      
      const lineEntity = viewer.entities.add({
        name: `禁飞区边缘线${i+1}`,
        polyline: {
          positions: [bottomPos, topPos],
          width: 2.5,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.3,
            color: Cesium.Color.RED.withAlpha(0.8),
            taperPower: 0.5
          })
        }
      });
      
      verticalLines.push(lineEntity);
    }
    
    // 添加禁飞区标签
    const labelPosition = Cartesian3.fromDegrees(
      center.longitude, 
      center.latitude, 
      fenceHeight + 20 // 标签位于围栏顶部上方20米
    );
    
    const label = viewer.entities.add({
      name: '禁飞区标签',
      position: labelPosition,
      label: {
        text: '⚠️ 禁飞区',
        font: '16px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.RED,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, -10),
        showBackground: true,
        backgroundColor: Cesium.Color.RED.withAlpha(0.7),
        backgroundPadding: new Cesium.Cartesian2(7, 5),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
    
    // 添加闪烁的警示灯
    const warningLight = viewer.entities.add({
      name: '禁飞区警示灯',
      position: labelPosition,
      point: {
        pixelSize: 12,
        color: Cesium.Color.RED,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
    
    // 添加闪烁效果
    const flashInterval = setInterval(() => {
      if (!warningLight || !viewer.entities.contains(warningLight)) {
        clearInterval(flashInterval);
        return;
      }
      
      // 切换点的可见性
      if (warningLight.point && warningLight.point.show) {
        warningLight.point.show = new Cesium.ConstantProperty(!warningLight.point.show.getValue());
      }
    }, 500); // 每500毫秒闪烁一次
    
    // 添加地面边界线，用于强调禁区边界
    const boundaryEntity = viewer.entities.add({
      name: '禁飞区地面边界',
      polyline: {
        positions: [
          Cartesian3.fromDegrees(corners[0].lon, corners[0].lat, 0.5), // 稍微抬高一点避免闪烁
          Cartesian3.fromDegrees(corners[1].lon, corners[1].lat, 0.5),
          Cartesian3.fromDegrees(corners[2].lon, corners[2].lat, 0.5),
          Cartesian3.fromDegrees(corners[3].lon, corners[3].lat, 0.5),
          Cartesian3.fromDegrees(corners[0].lon, corners[0].lat, 0.5) // 闭合
        ],
        width: 2,
        material: new Cesium.PolylineDashMaterialProperty({
          color: Cesium.Color.RED.withAlpha(0.8),
          dashLength: 16.0
        }),
        clampToGround: true
      }
    });
    
    // 清理函数
    const cleanup = () => {
      clearInterval(flashInterval);
      
      // 移除所有墙面
      walls.forEach(wall => viewer.entities.remove(wall));
      
      // 移除所有边缘线
      verticalLines.forEach(line => viewer.entities.remove(line));
      
      // 移除标签和警示灯
      viewer.entities.remove(label);
      viewer.entities.remove(warningLight);
      viewer.entities.remove(boundaryEntity);
    };
    
    return {
      walls,
      verticalLines,
      label,
      warningLight,
      boundaryEntity,
      cleanup
    };
  };
  
  // 添加新函数：从JSON文件加载禁飞区数据并创建2D平面多边形
  const createFlyZonesFromJSON = async (viewer: Cesium.Viewer) => {
    try {
      // 加载flyzone1.json数据
      const response1 = await fetch('/flyzone1.json');
      if (!response1.ok) {
        throw new Error('无法加载flyzone1数据');
      }
      const flyzone1 = await response1.json();
      
      // 加载flyzone2.json数据
      const response2 = await fetch('/flyzone2.json');
      if (!response2.ok) {
        throw new Error('无法加载flyzone2数据');
      }
      const flyzone2 = await response2.json();
      
      // 创建flyzone1的多边形
      createFlyZonePolygon(viewer, flyzone1, '低空经济产业园', Color.RED);
      
      // 创建flyzone2的多边形
      createFlyZonePolygon(viewer, flyzone2, '五邑大学', Color.RED);
      
      console.log('禁飞区数据加载完成');
    } catch (error) {
      console.error('加载禁飞区数据失败:', error);
      setError(`加载禁飞区数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };
  
  // 创建单个禁飞区多边形
  const createFlyZonePolygon = (viewer: Cesium.Viewer, zoneData: Array<{Longitude: number; Latitude: number; Elevation: number}>, zoneName: string, color: Cesium.Color) => {
    if (!zoneData || !zoneData.length) return;
    
    // 提取坐标点
    const positions = zoneData.map(point => 
      Cartesian3.fromDegrees(point.Longitude, point.Latitude, 1.0) // 将多边形略微抬高以避免与地面重叠
    );
    
    // 计算中心点（用于放置标签）
    let centerLon = 0, centerLat = 0;
    zoneData.forEach(point => {
      centerLon += point.Longitude;
      centerLat += point.Latitude;
    });
    
    centerLon /= zoneData.length;
    centerLat /= zoneData.length;
    
    // 创建多边形
    viewer.entities.add({
      name: `${zoneName}禁飞区`,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(positions),
        material: color.withAlpha(0.3),
        outline: true,
        outlineColor: color,
        outlineWidth: 2,
        height: 1.0, // 略微抬高多边形以避免与地面重叠
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
      }
    });
    
    // 创建边界线（更醒目）
    viewer.entities.add({
      name: `${zoneName}边界线`,
      polyline: {
        positions: [...positions, positions[0]], // 添加第一个点以闭合
        width: 2,
        material: new Cesium.PolylineDashMaterialProperty({
          color: color,
          dashLength: 16
        }),
        clampToGround: true
      }
    });
    
    // 添加标签
    viewer.entities.add({
      name: `${zoneName}标签`,
      position: Cartesian3.fromDegrees(centerLon, centerLat, 50), // 在中心点上方50米
      label: {
        text: `⚠️ ${zoneName}`,
        font: '16px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: color,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, 0),
        showBackground: true,
        backgroundColor: color.withAlpha(0.7),
        backgroundPadding: new Cesium.Cartesian2(7, 5),
        disableDepthTestDistance: Number.POSITIVE_INFINITY // 确保标签始终可见
      }
    });
  };
  
  // 修改雷达站函数，使用GLB模型
  const createRadarStation = (viewer: Cesium.Viewer) => {
    // 将雷达站放在合适的位置（禁飞区和航线范围外）
    const radarPosition = {
      longitude: 113.061850, // 向西偏移
      latitude: 22.610914, // 向北偏移
      height: -15 // 地面高度
    };
    
    // 雷达扫描范围半径（10公里）
    const radarRange = 10000;
    
    // 计算10公里在经纬度上的近似值（在当前纬度下）
    const oneDegreeLatInMeters = 111000; // 纬度1度约为111km
    const oneDegreeLonInMeters = 111000 * Math.cos(CesiumMath.toRadians(radarPosition.latitude)); // 根据纬度调整经度1度的距离
    
    // 使用GLB模型替代之前的几何体
    const modelEntity = viewer.entities.add({
      name: '航空监控雷达站',
      position: Cesium.Cartesian3.fromDegrees(
        radarPosition.longitude, 
        radarPosition.latitude, 
        radarPosition.height
      ),
      model: {
        uri: '/rts_radar_tower.glb',
        minimumPixelSize: 32, // 确保模型在远处仍然可见
        maximumScale: 20, // 限制最大缩放比例
        scale: 0.01, // 默认缩放比例 - 可根据实际模型大小调整
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 确保模型贴合地面
        shadows: Cesium.ShadowMode.ENABLED,
        runAnimations: true, // 如果模型有动画，启用它
        silhouetteColor: Cesium.Color.WHITE, // 模型轮廓颜色
        silhouetteSize: 0.5, // 轮廓宽度
        color: Cesium.Color.WHITE.withAlpha(1.0) // 模型颜色
      }
    });
    
    // 添加雷达站标签
    viewer.entities.add({
      name: '雷达站标签',
      position: Cesium.Cartesian3.fromDegrees(radarPosition.longitude, radarPosition.latitude, radarPosition.height + 20),
      label: {
        text: '航空监控雷达站',
        font: '14px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        pixelOffset: new Cesium.Cartesian2(0, -10),
        showBackground: true,
        backgroundColor: new Cesium.Color(0, 0.5, 0.8, 0.7),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
    
    // 创建雷达覆盖范围圆圈（静态显示）
    const radarRangeCircle = viewer.entities.add({
      name: '雷达覆盖范围',
      position: Cesium.Cartesian3.fromDegrees(radarPosition.longitude, radarPosition.latitude, radarPosition.height),
      ellipse: {
        semiMajorAxis: radarRange,
        semiMinorAxis: radarRange,
        height: 0,
        material: new Cesium.ColorMaterialProperty(Cesium.Color.CYAN.withAlpha(0.1)),
        outline: true,
        outlineColor: Cesium.Color.CYAN.withAlpha(0.6),
        outlineWidth: 2
      }
    });
    
    // 创建内部刻度圆
    const scaleCircles: Cesium.Entity[] = [];
    for (let i = 1; i <= 5; i++) {
      const radius = radarRange * (i / 5); // 以2km为间隔创建5个刻度圆
      const scaleCircle = viewer.entities.add({
        name: `雷达刻度圈 ${i}`,
        position: Cesium.Cartesian3.fromDegrees(radarPosition.longitude, radarPosition.latitude, radarPosition.height),
        ellipse: {
          semiMajorAxis: radius,
          semiMinorAxis: radius,
          height: 0,
          material: Cesium.Color.TRANSPARENT,
          outline: true,
          outlineColor: Cesium.Color.CYAN.withAlpha(0.4),
          outlineWidth: 1.0
        }
      });
      scaleCircles.push(scaleCircle);
      
      // 为每个刻度圈添加距离标签
      const labelAngle = 45; // 在东北方向添加标签
      const labelLon = radarPosition.longitude + Math.cos(CesiumMath.toRadians(labelAngle)) * (radius / oneDegreeLonInMeters);
      const labelLat = radarPosition.latitude + Math.sin(CesiumMath.toRadians(labelAngle)) * (radius / oneDegreeLatInMeters);
      
      viewer.entities.add({
        name: `雷达距离标签 ${i}`,
        position: Cesium.Cartesian3.fromDegrees(labelLon, labelLat, radarPosition.height + 1),
        label: {
          text: `${(radius / 1000).toFixed(0)}km`,
          font: '12px sans-serif',
          fillColor: Cesium.Color.CYAN,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          show: true
        }
      });
    }
    
    // 创建方向标记 (N, E, S, W)
    const directionLabels = ['N', 'E', 'S', 'W'];
    const directionAngles = [0, 90, 180, 270]; // 北东南西对应的角度
    
    for (let i = 0; i < 4; i++) {
      const angle = directionAngles[i];
      const dirLon = radarPosition.longitude + Math.sin(CesiumMath.toRadians(angle)) * (radarRange * 1.05 / oneDegreeLonInMeters);
      const dirLat = radarPosition.latitude + Math.cos(CesiumMath.toRadians(angle)) * (radarRange * 1.05 / oneDegreeLatInMeters);
      
      viewer.entities.add({
        name: `方向标记 ${directionLabels[i]}`,
        position: Cesium.Cartesian3.fromDegrees(dirLon, dirLat, radarPosition.height + 1),
        label: {
          text: directionLabels[i],
          font: '14px sans-serif',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        }
      });
    }
    
    // 返回清理函数
    return () => {
      viewer.entities.remove(modelEntity);
      viewer.entities.remove(radarRangeCircle);
      scaleCircles.forEach(circle => viewer.entities.remove(circle));
    };
  };
  
  return (
    <MapContainer>
      {isLoading && (
        <MapLoadingOverlay>
          加载地图中，请稍候...
        </MapLoadingOverlay>
      )}
      
      {error && (
        <MapLoadingOverlay>
          {error}
        </MapLoadingOverlay>
      )}
      
      {terrainLoading && !isLoading && !error && (
        <MapLoadingOverlay>
          加载3D地形中，请稍候...
        </MapLoadingOverlay>
      )}
      
      <Viewer
        full
        timeline={false}
        animation={false}
        baseLayerPicker={false}
        geocoder={false}
        homeButton={false}
        navigationHelpButton={false}
        sceneModePicker={false}
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          width: '100%',
          height: '100%'
        }}
        ref={(e) => {
          if (e && e.cesiumElement && !viewerRef.current) {
            handleViewerReady(e.cesiumElement);
          }
        }}
        terrainProvider={new Cesium.EllipsoidTerrainProvider()}
        scene3DOnly={true}
        requestRenderMode={false}
        shouldAnimate={true}
      >
        {/* 调整光照效果 */}
        <Entity
          name="全局光照调整"
          position={Cartesian3.fromDegrees(0, 0, 0)}
          point={{ pixelSize: 0, color: Color.TRANSPARENT }}
        />
        
        {/* 北斗网格图层 */}
        {isGridVisible && viewerRef.current && (
          <BeidouGridLayer
            viewer={viewerRef.current}
            gridLevel={gridLevel}
            maxHeight={5000}
            showGridCodes={true}
            enableDynamicLevel={false}
          />
        )}
      </Viewer>
      
      {/* 实时无人机位置数据图层 */}
      {viewerRef.current && (
        <RealtimeDroneLayer viewer={viewerRef.current} />
      )}
      
      {/* 固定位置的无人机信息气泡 */}
      {droneInfoData && (
        <DroneInfoBubble style={{ display: showDroneInfo ? 'block' : 'none' }}>
          <div className="bubble-header">
            <span>巡检无人机信息</span>
            <span className="close-btn" onClick={() => setShowDroneInfo(false)}>×</span>
          </div>
          <table>
            <tbody>
              <tr><td>经度:</td><td>{droneInfoData.longitude.toFixed(6)}°</td></tr>
              <tr><td>纬度:</td><td>{droneInfoData.latitude.toFixed(6)}°</td></tr>
              <tr><td>高度:</td><td>{droneInfoData.height.toFixed(1)}米</td></tr>
              <tr><td>SN码:</td><td>{droneInfoData.sn}</td></tr>
              <tr><td>登记标志:</td><td>{droneInfoData.regCode}</td></tr>
              <tr><td>所有人:</td><td>{droneInfoData.owner}</td></tr>
              <tr><td>所属单位:</td><td>{droneInfoData.organization}</td></tr>
              <tr><td>型号:</td><td>{droneInfoData.model}</td></tr>
              <tr><td>用途:</td><td>{droneInfoData.purpose}</td></tr>
            </tbody>
          </table>
        </DroneInfoBubble>
      )}
      
      {!isLoading && !error && (
        <>
          <MapToolbar>
            <ComponentTitle>地图工具</ComponentTitle>
            <ToolButton onClick={handleZoomIn} title="放大">+</ToolButton>
            <ToolButton onClick={handleZoomOut} title="缩小">-</ToolButton>
            <ToolButton onClick={handleResetView} title="重置视图">↺</ToolButton>
            <ToolButton onClick={toggleTerrain} title="切换地形">🌋</ToolButton>
            <ToolButton 
              onClick={toggleMapType} 
              title={isSatelliteMap ? "切换到矢量地图" : "切换到卫星地图"}
            >
              {isSatelliteMap ? "🗺️" : "🛰️"}
            </ToolButton>
            <ToolButton 
              onClick={toggleAnnotation} 
              title={isAnnotationVisible ? "隐藏路网" : "显示路网"}
              style={{ color: isAnnotationVisible ? '#ffffff' : '#888888' }}
            >
              🛣️
            </ToolButton>
            <ToolButton 
              onClick={toggleGrid} 
              title={isGridVisible ? "隐藏网格" : "显示网格"}
              style={{ color: isGridVisible ? '#ffffff' : '#888888' }}
            >
              🧩
            </ToolButton>
            {isGridVisible && (
              <ToolButton 
                onClick={cycleGridLevel} 
                title={`当前级别: ${gridLevel} (点击切换)`}
              >
                L{gridLevel}
              </ToolButton>
            )}
          </MapToolbar>
          
          <OverlayContainer>
            <ComponentTitle>位置信息</ComponentTitle>
            <CoordinateInfo>
              <Label>经度:</Label>
              <Value>{mousePosition ? mousePosition.longitude.toFixed(6) : '---'}°</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>纬度:</Label>
              <Value>{mousePosition ? mousePosition.latitude.toFixed(6) : '---'}°</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>高度:</Label>
              <Value>{mousePosition ? Math.round(mousePosition.height) : '---'}米</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>俯仰:</Label>
              <Value>{Math.round(position.pitch)}°</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>朝向:</Label>
              <Value>{Math.round(position.heading)}°</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>地形:</Label>
              <Value>{terrainEnabled ? '开启' : '关闭'}</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>地图:</Label>
              <Value>{isSatelliteMap ? '卫星图' : '矢量图'}</Value>
            </CoordinateInfo>
            <CoordinateInfo>
              <Label>路网:</Label>
              <Value>{isAnnotationVisible ? '显示' : '隐藏'}</Value>
            </CoordinateInfo>
            {isGridVisible && (
              <CoordinateInfo>
                <Label>网格:</Label>
                <Value>级别 {gridLevel}</Value>
              </CoordinateInfo>
            )}
          </OverlayContainer>
        </>
      )}
    </MapContainer>
  );
} 